package com.wang.springbootinit.Listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wang.springbootinit.common.ErrorCode;
import com.wang.springbootinit.constant.MQConstant;
import com.wang.springbootinit.exception.BusinessException;
import com.wang.springbootinit.model.dto.chart.GenChartByAiRequest;
import com.wang.springbootinit.model.entity.Chart;
import com.wang.springbootinit.model.entity.User;
import com.wang.springbootinit.model.enums.ChartStatusEnum;
import com.wang.springbootinit.service.ChartService;
import com.wang.springbootinit.service.UserService;
import com.wang.springbootinit.service.impl.GenChart.GenChartAfterHandler;
import com.wang.springbootinit.sparkAi.AiAnalyseModel;
import com.wang.springbootinit.sparkAi.AiAnalyseQueryParam;
import com.wang.springbootinit.sparkAi.AnalyseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
@RocketMQMessageListener(consumerGroup = MQConstant.ANALYSE_GROUP, topic = MQConstant.ANALYSE_TOPIC)
public class GenChartAsyncConsumer implements RocketMQListener<MQGenChartAsyncModel> {
    private static final Logger LOGGER = LoggerFactory.getLogger(GenChartAsyncConsumer.class);

    @Resource
    private AnalyseService analyseService;
    @Resource
    private GenChartAfterHandler genChartAfterHandler;
    @Resource
    private ChartService chartService;
    @Resource
    private UserService userService;

    @Override
    public void onMessage(MQGenChartAsyncModel model) {
        LOGGER.info("GenChartAsyncConsumer onMessage message:{}", JSONUtil.toJsonStr(model));
        try {
            if (ObjectUtil.isNotNull(model)) {
                handler(model);
            }
        } catch (Exception e) {
            LOGGER.info("GenChartAsyncConsumer onMessage exception:",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 具体处理逻辑
     * @param model
     */
    private void handler(MQGenChartAsyncModel model) {
        //执行状态  等待-》 执行中 -》 成功
        UpdateWrapper<Chart> chartUpdateWrapper = new UpdateWrapper<>();
        Chart chartRunning = new Chart();
        chartRunning.setId(model.getChartId());
        chartRunning.setStatus(ChartStatusEnum.RUNNING.getValue()); //设置为执行中
        boolean updateById = chartService.updateById(chartRunning);
        if (!updateById) {
            handleErrorChart(model.getChartId(), "更新图表状态 wait->running 失败");
            return;
        }
        //分析处理
        AiAnalyseModel aiAnalyseModel = analyseService.syncChat(new AiAnalyseQueryParam(model.getContent()));

        User user = userService.getById(model.getUserId());
        Chart chart = chartService.getById(model.getChartId());
        GenChartByAiRequest chartByAiRequest = new GenChartByAiRequest();
        chartByAiRequest.setChartType(chart.getChartType());
        chartByAiRequest.setName(chart.getName());
        chartByAiRequest.setGoal(chart.getGoal());

        //后置处理
        genChartAfterHandler.syncGenChartHandler(user, chartByAiRequest, aiAnalyseModel, chart.getChartData());

        //处理文件未补充的字段
        // TODO: 2024/3/20
    }

    /**
     * 处理图表状态保存失败
     *
     * @param chartId
     * @param errMessage
     */
    private void handleErrorChart(Long chartId, String errMessage) {
        //保存失败
        Chart tempChart = new Chart();
        tempChart.setId(chartId);
        tempChart.setStatus(ChartStatusEnum.FAILED.getValue()); //设置为失败
        tempChart.setExecMessage(errMessage);
        boolean tempRes = chartService.updateById(tempChart);
        if (!tempRes) {
            //一般不会失败
            LOGGER.error("更新图表状态失败");
        }
    }
}
